package top.tenebrous.yzl.im.listener;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import top.tenebrous.yzl.im.contants.RedisConstants;

/**
 *  消息监听对象，接收订阅消息
 *
 * @author yazhang6
 */
@Slf4j
@Component
public class RedisReceiverListener implements MessageListener {

    @Autowired
    private ReceiverMessageHandler receiverMessageHandler;
    
    @Override
    public void onMessage(Message message, byte[] pattern) {
        log.info("接收到redis队列数据:{}", JSON.toJSONString(message));
        // 获取订阅的频道名称
        String channel = new String(message.getChannel());
        String msg = "";
        try {
            // 注意与发布消息编码一致，否则会乱码
            msg = new String(message.getBody(), RedisConstants.UTF8);
            if (StringUtils.isNotEmpty(msg)){
                receiverMessageHandler.handlerMessage(msg, channel);
            }else{
                log.info("消息内容为空，不处理。");
            }
        } catch (Exception e) {
            log.error("处理消息异常：{}",e);
        }
    }

}